import { useState, useEffect } from 'react';

/**
 * 防抖Hook - 延迟执行值的更新
 * @param {any} value - 需要防抖的值
 * @param {number} delay - 延迟时间(毫秒)
 * @returns {any} 防抖后的值
 */
export const useDebounce = (value, delay) => {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);

        return () => {
            clearTimeout(handler);
        };
    }, [value, delay]);

    return debouncedValue;
};

/**
 * 防抖回调Hook - 防抖执行函数
 * @param {Function} callback - 要防抖的回调函数
 * @param {number} delay - 延迟时间(毫秒)
 * @param {Array} deps - 依赖数组
 */
export const useDebouncedCallback = (callback, delay, deps) => {
    const [debouncedCallback, setDebouncedCallback] = useState(null);

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedCallback(() => callback);
        }, delay);

        return () => {
            clearTimeout(handler);
        };
    }, [...(deps || []), delay]);

    return debouncedCallback;
};
